﻿using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Reflection;
using System.Threading.Tasks;
using WPFExcelReport.Helpers;
using WPFExcelReport;
namespace INTEXReportSrv
{

    public class SignalRServer
    {
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        const int NumOfThread = 2;
        public bool IsListening { get; private set; } 
      
        private Thread _listenthread;
         public Dictionary<string, object> ENVMAIN
        {
            get
            {
                return app.ENVMAIN(app.ServiceUri);
            }
        }
        public IDisposable SignalR { get; set; }
        public string ServerURI = "";
        ZLANClient Client;
        Dictionary<string, ZLANClient> _Clients;
        public Dictionary<string, ZLANClient> Clients
        {
            get
            {
                if (_Clients == null)
                {
                    _Clients = new Dictionary<string, ZLANClient>();
                }
                return _Clients;
            }
        } 
        public SignalRServer(int pointInt)
        {
            IsListening = false;
            ServerURI = "http://"+app.ServiceUri+":"+ pointInt.ToString(); 
        }
        public void StartListen()
        {
            if (IsListening)
                return;
            Task.Run(() => StartServer());
            /*
            IsListening = true;  
            _listenthread = new Thread(StartServer);
            _listenthread.Start();*/
        }
        private void StartServer()
        {
            try
            {
                SignalR = WebApp.Start(ServerURI);
                IsListening = true;
            }
            catch (TargetInvocationException)
            {
                LogHelper.info("A server is already running at " + ServerURI);
                return;
            }
            LogHelper.info("Server started at " + ServerURI);
        }
       
    }
    class Startup
    {
        public void Configuration(IAppBuilder TVApp)
        {
            TVApp.UseCors(CorsOptions.AllowAll);
            TVApp.MapSignalR();
        }
    }
}
 